﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Orange.Logistics.Infrastructure;
using Orange.Logistics.Models;
using Orange.Logistics.Services;
using System;
using Newtonsoft.Json;

namespace Orange.Logistics.Controllers {

    public class ModuleController : BaseController<Module> {

        private readonly IModuleService service;

        public ModuleController(IModuleService service)
            : base(service) {
            this.service = service;
        }

        public override JsonResult GetGrid() {
            InitPager();
            int parendid = int.Parse(PG.parms);
            var list = service.List(m => m.ParentId == parendid);
            int total = list.Count();
            IEnumerable<Module> source = null;
            if (PG.asc) {
                source = list.OrderBy(GetOrderBy(PG.sort));
            } else {
                source = list.OrderByDescending(GetOrderBy(PG.sort));
            }
            return Json(new { Rows = PagedList<Module>(source), Total = total });
        }

        public JsonResult GetTree() {
            var topMenus = service.GetModules(m => m.ParentId == 0 && m.Status != "D")
                                  .OrderBy(GetOrderBy("Sort"))
                                  .Select(m =>
                                        new TreeNode {
                                            id = m.Id, text = m.ModuleName,
                                            icon = Url.Content(m.ModuleIcon)
                                        });
            return Json(new List<TreeNode> { 
                    new TreeNode { 
                        id = 0,
                        text = "全部模块",
                        children = topMenus } 
            }, JsonRequestBehavior.AllowGet);
        }

        protected override Func<Module, object> GetOrderBy(string sort) {
            return (Module m) => {
                switch (sort) {
                    case "ModuleName":
                        return m.ModuleName;
                    case "ModuleLinkUrl":
                    case "ModuleController":
                        return m.ModuleController;
                    case "Sort":
                        return m.Sort;
                    default:
                        return m.Id;
                }
            };
        }

        protected override void Dispose(bool disposing) {
            if (disposing) {
                service.Dispose();
            }
        }
    }
}
